﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Mine
{
    class InterlockedLockingStationActive : SimpleStation
    {

        private int locker = 0;
        //mindig a kisebb ID-jű lockolódik első körben
        public override double MoveStones(int Amount, IStation Destination)
        {
            if (this.ID < Destination.ID)//nagyobb ID-jű
            {
                return LockThisFirst((-1) * Amount, (InterlockedLockingStationActive)Destination);
            }
            else
            {
                //a destination lock-this-first-je
                return ((InterlockedLockingStationActive)Destination).LockThisFirst(Amount, this);
            }
        }
        public double LockThisFirst(int Amount, InterlockedLockingStationActive station)
        {
            //0 indicates that the method is not in use.
            while (0 != Interlocked.Exchange(ref locker, 1)) { }
            //addig próbálkozunk amíg nem találjuk 0-nak a lockert
            double r = station.LockAfterFirst(Amount, this);

            //Release the lock
            Interlocked.Exchange(ref locker, 0);

            return r;
        }
        public double LockAfterFirst(int Amount, InterlockedLockingStationActive station)
        {
            //0 indicates that the method is not in use.
            while (0 != Interlocked.Exchange(ref locker, 1)) { }

            double r = base.MoveStones(Amount, station);//a nagyobb ID-jű moveStones-a fut le

            //Release the lock
            Interlocked.Exchange(ref locker, 0);

            return r;
        }
    }
}
